//
//  ICNoticeViewController.m
//  ICome
//
//  Created by zhangrongwu on 2017/6/30.
//  Copyright © 2017年 iCom. All rights reserved.
//

#import "ICNoticeViewController.h"
#import "ICChatHearder.h"
#import "ICMessageNetworkManager.h"
#import "ICMessageSocketManager.h"
#import "YYPhotoGroupView.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "iComeApiManager.h"

@interface ICNoticeViewController()<UITableViewDataSource, UITableViewDelegate, ICGtasksTableViewCellDelegate, ChatAdaptBaseCellDelete>

@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) ICGroup *group;

@property (nonatomic, strong)ICEmptyStyleView *emptyView;

@end

@implementation ICNoticeViewController
#pragma mark - life cycle
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    if (!self.group) {
        self.group = self.parameterDictionary[@"group"];
    }
    [self registerCell];
    [self setUI];
    [self setNav];
    [self getData];
    [self initNotificationCenter];
}

- (void)initNotificationCenter {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(messageDidReceivedUpdate:) name:NotificationReceiveMessageUpdate object:nil];
}

- (void)messageDidReceivedUpdate:(NSNotification *)notifi {
    NSDictionary *dic = notifi.object;
    ICMessageFrame *messageF = (ICMessageFrame *)[dic objectForKey:@"ICMessageFrame"];
    
    if ([messageF.model.message.to isEqualToString:self.group.gId]) {
        [self.dataSource insertObject:messageF atIndex:0];
        [self.tableView reloadData];
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [ICMessageDatabase updateGroupUnreadMessageCountWithGroupId:self.group.gId count:0]; // 清除未读数
    [ICMessageDatabase updateGroupAlertStatus:0 gId:self.group.gId];
    [ICMessageHelper updateGroupReadWithGroupId:self.group.gId];
}

- (void)endRefreshing
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self.tableView reloadData];
    });
}

- (void)loadDataSource
{
    WEAKSELF
    [ICMessageDatabase selectASCMessageWithCount:20 group:self.group.gId firstMessage:nil finish:^(NSArray *array, NSError *error) {
        // 数组逆序处理
        NSArray *list =  [[array reverseObjectEnumerator] allObjects];
        if (list.count>0) {
            [weakSelf.dataSource removeAllObjects];
            [weakSelf.dataSource addObjectsFromArray:list];
            weakSelf.emptyView.hidden = YES;
            
            
            if ([weakSelf.group.gId hasPrefix:@"tdo_"]) {
                weakSelf.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithTitle:@"清除未读" itemType:UIBarButtonItemTypeRight target:weakSelf action:@selector(rightBarButtonClicked)];
            } else {
                weakSelf.navigationItem.rightBarButtonItems = @[[[UIBarButtonItem alloc] initWithCustomView:[[UIView alloc] init]]];
            }
            
        } else {
            weakSelf.dataSource = nil;
            weakSelf.emptyView.hidden = NO;
        }
        [weakSelf endRefreshing];
    }];
}

- (void)loadMoreData
{
    WEAKSELF
    ICMessageFrame *modelFrame = self.dataSource.lastObject;
    [ICMessageDatabase selectASCMessageWithCount:20 group:self.group.gId firstMessage:modelFrame.model.message finish:^(NSArray *array, NSError *error) {
        NSArray *list =  [[array reverseObjectEnumerator] allObjects];
        if (list.count>0) {
            [weakSelf.dataSource addObjectsFromArray:list];
            [weakSelf endRefreshing];
        } else {
            NSString *maxIndex = modelFrame.model.message.messageId;
            if (maxIndex == nil) {
            }
            int index = maxIndex.intValue;
            if (index == 0 || index == 1) { // 已经是最后一条了
                dispatch_async(dispatch_get_main_queue(), ^{
                    [weakSelf endRefreshing];
                });
            } else {
                NSDictionary *param = @{@"gId":self.group.gId,
                                        @"maxIndex":[maxIndex numberValue] == nil ? @0:[maxIndex numberValue],
                                        @"size":@20};
                [self repullMessage:param with:modelFrame.model.message];
            }
        }
    }];
}

- (void)repullMessage:(NSDictionary *)param with:(ICMessage *)message
{
    WEAKSELF
    [[ICSocketRequestManager sharedInstance] repullMessageWithObject:param Success:^(id response) {
        // 后台返的消息id是从小到大
        NSArray *data = [response objectForKey:@"data"];
        if (data.count > 0) {
            for (NSDictionary *dic in data) {
                [ICMessageHelper messageTypeWithMessage:dic finished:^(ICMessageFrame *messageF) {
                    [ICMessageDatabase saveMessage:messageF.model]; // 统一存储消息
                }];
            }
            [weakSelf loadMoreData];
        } else {
            [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
        }
    } Failure:^(NSError *error, id other) {
        [self.tableView.mj_header endRefreshing];
    }];
}


#pragma mark - Tableview data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    id obj = self.dataSource[indexPath.row];
    if ([obj isKindOfClass:[NSString class]]) {
        return [[UITableViewCell alloc] init];
    } else {
        ICMessageFrame *modelFrame = (ICMessageFrame *)obj;
        NSString *identifier = modelFrame.model.message.type;
        if ([identifier isEqualToString:TypeSystem]) {
            ICChatSystemCell *cell = [ICChatSystemCell cellWithTableView:tableView reusableId:TypeSystem];
            cell.messageF = modelFrame;
            return cell;
            
        } else if ([identifier isEqualToString:TypeChance]) {
            ICChnMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
            cell.message = [ICMessageHelper getChnModelModelWith:modelFrame.model.message];
            cell.backgroundColor = [UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
            
        } else if ([identifier isEqualToString:TypeNotif]) {
            ICNotifyMsgCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
            ICNotify *notify = [ICMessageHelper getNotifyModelModelWith:modelFrame.model.message];
            cell.message = notify;
            cell.backgroundColor = [UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            if ([self.group.gId hasPrefix:@"ntf_"]) {
                cell.unreadPoint.hidden = YES;
            }
            return cell;
            
        } else if ([identifier isEqualToString:TypePending]) {
            ICGtasksTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
            cell.model = [ICMessageHelper getGtasksModelWith:modelFrame.model.message];
            cell.dateLabel.hidden = YES;
            cell.delegate = self;
            cell.backgroundColor = [UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
            
        } else if ([identifier isEqualToString:TypeDrtNews]) {
            ICBaseNoticeCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell) {
                cell = [[ICBaseNoticeCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            }
            cell.modelFrame = modelFrame;
            cell.backgroundColor = [UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
            
        } else if ([identifier isEqualToString:TypeActivity]) {
            ICActivityTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
            cell.modelFrame = modelFrame;
            cell.backgroundColor = [UIColor clearColor];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
            
        } else if ([identifier compare:@"999" options:NSNumericSearch] != NSOrderedAscending) {
            
            ICChatAdaptBaseCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
            if (!cell) {
                cell = [[ICChatAdaptBaseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            }
            cell.longPressDelegate = self;
            NSString *nName = [ICMessageDatabase nickNameWithEid:modelFrame.model.message.from
                                                             gId:modelFrame.model.message.to];
            [self setCell:cell rowAtIndexPath:indexPath nName:nName];
            return cell;
        }
        ICChatMessageBaseCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[ICChatMessageBaseCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        if ([identifier isEqualToString:TypeFile]) {
            NSLog(@"");
        }
        cell.modelFrame = modelFrame;
        return cell;
    }
}

- (void)setCell:(ICChatAdaptBaseCell *)cell rowAtIndexPath:(NSIndexPath *)indexPath nName:(NSString *)nName{
    ICMessageFrame *modelFrame = self.dataSource[indexPath.row];
    // set 数据
    cell.data = @{@"type":modelFrame.model.message.type,
                  @"txt":modelFrame.model.message.content,
                  @"fr":modelFrame.model.message.from,
                  @"to":self.group.gId,
                  @"data":modelFrame.model.message.fileKey,
                  @"nName":nName
                  };
}
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ICMessageFrame *messageF = [self.dataSource objectAtIndex:indexPath.row];
    NSString *identifier = messageF.model.message.type;

    if ([identifier compare:@"999" options:NSNumericSearch] != NSOrderedAscending) {
        return [tableView fd_heightForCellWithIdentifier:identifier cacheByIndexPath:indexPath configuration:^(ICChatAdaptBaseCell *cell) {
            [self setCell:cell rowAtIndexPath:indexPath nName:@""];
        }];
    }
    return messageF.cellHight;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ICMessageFrame *messageFrame = [self.dataSource objectAtIndex:indexPath.row];
    NSString *identifier = [NSString stringWithFormat:@"%@",messageFrame.model.message.type];
    NSString *link = messageFrame.model.message.lnk;
    if (![ICTools stringEmpty:link]) {
        if ([identifier isEqualToString:TypeChance]) {
            [self pushCustomViewControllerURL:link fromViewController:self animated:YES];
            // 更新具体某条消息是否已读
            NSString *meaasgeId = [NSString stringWithFormat:@"%@",messageFrame.model.message.messageId];
            [self updateMessageReadStatus:meaasgeId];
            [self.tableView reloadData];
        }
    }
    
    // 用于外部自定义消息体
    if ([identifier compare:@"999" options:NSNumericSearch] != NSOrderedAscending) {
        if ([[iComeApiManager instance].delegate respondsToSelector:@selector(tableView:didSelectRowAtIndexPath:select:)]) {
            NSDictionary  *data = @{@"type":messageFrame.model.message.type,
                                    @"txt":messageFrame.model.message.content,
                                    @"fr":messageFrame.model.message.from,
                                    @"to":self.group.gId,
                                    @"data":messageFrame.model.message.fileKey,
                                    @"nName":@""
                                    };
            [[iComeApiManager instance].delegate tableView:tableView didSelectRowAtIndexPath:indexPath select:data];
        }
    }
}

- (void)longPress:(UILongPressGestureRecognizer *)longRecognizer {
    NSLog(@"长按暂不处理");
}

#pragma mark - CustomDelegate
- (void)didClickPendingSureBtnInCell:(ICGtasksTableViewCell *)cell {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    // 对中间层进行转换
    ICMessageFrame *modelFrame = self.dataSource[indexPath.row];
    ICGtasksModel *model = [ICMessageHelper getGtasksModelWith:modelFrame.model.message];
    NSString *url = [model appendUserInfoforJSURL:model.confirmurl msgId:model.msgId];
    [MBProgressHUD showMessage:@"正在处理" toView:self.view];
    [[ICApplicationNetworkManager sharedInstance] gtaskConfirmurl:url success:^(id object) {
        [MBProgressHUD hideHUDForView:self.view];
        [ICMessageDatabase setGtasksMsgId:model.msgId Status:[NSString stringWithFormat:@"%d", TodoStatus_Confirm]]; // 数据库变动
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:@"提交失败"];
    }];
}


- (void)didClickPendingCancelBtnInCell:(ICGtasksTableViewCell *)cell {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    ICMessageFrame *modelFrame = self.dataSource[indexPath.row];
    ICGtasksModel *model = [ICMessageHelper getGtasksModelWith:modelFrame.model.message];
    
    NSString *url = [model appendUserInfoforJSURL:model.rejecturl msgId:model.msgId];
    [MBProgressHUD showMessage:@"正在处理" toView:self.view];
    [[ICApplicationNetworkManager sharedInstance] gtaskRejecturl:url success:^(id object) {
        [MBProgressHUD hideHUDForView:self.view];
        [ICMessageDatabase setGtasksMsgId:model.msgId Status:[NSString stringWithFormat:@"%d", TodoStatus_Reject]];
        
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:@"提交失败"];
    }];
}

- (void)didClickPendingDetailBtnInCell:(ICGtasksTableViewCell *)cell {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    ICMessageFrame *modelFrame = self.dataSource[indexPath.row];
    ICGtasksModel *model = [ICMessageHelper getGtasksModelWith:modelFrame.model.message];
    if (![ICTools stringEmpty:model.openurl]) {
        [self pushCustomViewControllerURL:model.openurl fromViewController:self animated:YES];
    }
}

#pragma mark - event response
// 按钮点击方法
#pragma mark - private methods

- (void)registerCell
{
    [self.tableView registerClass:[ICChatMessageTextCell class] forCellReuseIdentifier:TypeText];
    [self.tableView registerClass:[ICChatMessageImageCell class] forCellReuseIdentifier:TypePic];
    [self.tableView registerClass:[ICChatMessageVideoCell class] forCellReuseIdentifier:TypeVideo];
    [self.tableView registerClass:[ICChatMessageVoiceCell class] forCellReuseIdentifier:TypeVoice];
    [self.tableView registerClass:[ICChatMessageFileCell class] forCellReuseIdentifier:TypeFile];
    [self.tableView registerClass:[ICChatMessageShareCell class] forCellReuseIdentifier:TypePicText];
    [self.tableView registerClass:[ICChatMessageRedPacketCell class] forCellReuseIdentifier:TypeRedPacket];
    [self.tableView registerClass:[ICChatMessageATTextCell class] forCellReuseIdentifier:TypeAtText];
    [self.tableView registerClass:[ICChatMessageConferenceCell class] forCellReuseIdentifier:TypeVideoConference];
    [self.tableView registerClass:[ICNotifyMsgCell class] forCellReuseIdentifier:TypeNotif];
    [self.tableView registerClass:[ICChnMessageCell class] forCellReuseIdentifier:TypeChance];
    [self.tableView registerClass:[ICGtasksTableViewCell class] forCellReuseIdentifier:TypePending];
    [self.tableView registerClass:[ICNoticeDrtNewsCell class] forCellReuseIdentifier:TypeDrtNews];
    [self.tableView registerClass:[ICActivityTableViewCell class] forCellReuseIdentifier:TypeActivity];
    
    // 用于动态注册
    NSArray *cellClassList =[[NSUserDefaults standardUserDefaults] valueForKey:@"cellClassList"];
    
    for (NSDictionary *dict in cellClassList) {
        NSString *class = dict[@"class"];
        NSString *identifier = dict[@"id"];
        if (![ICTools stringEmpty:class] && ![ICTools stringEmpty:identifier]) {
            [self.tableView registerClass:NSClassFromString(class) forCellReuseIdentifier:identifier];
        }
    }
}

// 设置页面布局
- (void)setUI {
    [self.view addSubview:self.tableView];

//    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.view.mas_top);
//        make.left.equalTo(self.view.mas_left);
//        make.right.equalTo(self.view.mas_right);
//        make.bottom.equalTo(self.view.mas_bottom);
//    }];
    self.tableView.frame = CGRectMake(0, 0, App_Frame_Width, APP_Frame_Height - [ICTools getNavbarHeight]-[ICTools getStatusbarHeight]);
    
    WEAKSELF
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadDataSource];
    }];
    
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
//    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        [weakSelf loadMoreData];
//    }];
}

// 设置navigation
- (void)setNav {
    self.title = self.group.gName;
    self.navigationItem.rightBarButtonItem = nil;

}
// 网络请求
- (void)getData {
    [self loadDataSource];
}

- (void)rightBarButtonClicked {
    
    NSString *message = @"将全部待办消息设为已读？";
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                   message:message
                                                            preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消"
                                                           style:UIAlertActionStyleCancel
                                                         handler:nil];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定"
                                                       style:UIAlertActionStyleDefault
                                                     handler:^(UIAlertAction *action) {
                                                         [ICMessageDatabase selectAllMessage:self.group.gId finish:^(NSArray *array, NSError *error) {
                                                             dispatch_async(dispatch_get_main_queue(), ^{
                                                                 for (ICMessageFrame *messageFrame in array) {
                                                                     if (messageFrame.model.message.status == ICMessageStatus_unRead && ![ICTools stringEmpty:messageFrame.model.message.messageId]) {
                                                                         [ICMessageDatabase changeMessageStatus:messageFrame.model.message status:ICMessageStatus_read];
                                                                     }
                                                                 }
                                                                 [MBProgressHUD showSuccess:@"清除成功"];
                                                             });
                                                         }];
                                                     }];
    
    [alert addAction:okAction];
    [alert addAction:cancelAction];
    [App_RootCtr presentViewController:alert animated:YES completion:nil];
    
}
// 路由响应
- (void)routerEventWithName:(NSString *)eventName
                   userInfo:(NSDictionary *)userInfo
{
    ICMessageFrame *modelFrame = [userInfo objectForKey:MessageKey];
    if ([eventName isEqualToString:GXRouterEventTextUrlTapEventName]) {
        
    } else if ([eventName isEqualToString:GXRouterEventImageTapEventName]) {
        NSString *imgPath = modelFrame.model.mediaPath;
        NSString *orgImgPath = [[ICMediaManager sharedManager] originImgPath:modelFrame];
        if ([ICFileTool fileExistsAtPath:orgImgPath]) {
            modelFrame.model.mediaPath = orgImgPath;
            imgPath = orgImgPath;
        }
        [self showLargeImageWithOglImage:[userInfo objectForKey:@"oglImage"]
                                WithPath:imgPath
                            withMessageF:modelFrame
                                fromView:[userInfo objectForKey:@"obj"]
                             currentCell:[userInfo objectForKey:@"currentCell"]];
        
    } else if ([eventName isEqualToString:GXRouterEventVoiceTapEventName]) {
        // 语音
        //                UIImageView *imageView = (UIImageView *)userInfo[VoiceIcon];
        //                UIView *redView        = (UIView *)userInfo[RedView];
        //                [self chatVoiceTaped:modelFrame voiceIcon:imageView redView:redView];
    } else if ([eventName isEqualToString:GXRouterEventVideoTapEventName]) {
        //        [self showLargeVideoWithOglImage:[userInfo objectForKey:@"oglImage"] fromView:[userInfo objectForKey:@"obj"] currentCell:[userInfo objectForKey:@"currentCell"]];
    } else if ([eventName isEqualToString:GXRouterEventShareTapEvent]) {
        // 图片链接点击
        [self pushCustomViewControllerURL:modelFrame.model.message.lnk
                       fromViewController:self
                                 animated:YES];
    } else if ([eventName isEqualToString:GXRouterEventURLSkip]) {
        [self pushCustomViewControllerURL:[userInfo objectForKey:@"url"]
                       fromViewController:self
                                 animated:YES];
    } else if ([eventName isEqualToString:GXRouterEventScanFile]) {
        NSString *filePath = [userInfo objectForKey:@"filePath"];
        if ([[[NSDictionary dictionaryWithJsonString:modelFrame.model.message.lnk] objectForKey:@"x"] intValue] == ICFileType_Video){
            UIButton *btn = (UIButton *)[userInfo objectForKey:@"fileBtn"];
            
            NSMutableArray *items = [[NSMutableArray alloc] init];
            ICAVPlayerGroupItem *item = [ICAVPlayerGroupItem new];
            item.thumbView = btn;
            item.videoPath = filePath;
            [items addObject:item];
            
            ICAVPlayer *player = [[ICAVPlayer alloc] initWithGroupItems:items];
            [player presentFromVideoView:btn toContainer:App_RootCtr.view animated:YES completion:nil];
        } else {
            NSString *lnk = modelFrame.model.message.lnk;
            NSDictionary *dicLnk = [NSDictionary dictionaryWithJsonString:lnk];
            NSString *name  = [dicLnk objectForKey:@"n"];
            ICFileScanController *scanVC = [[ICFileScanController alloc] init];
            scanVC.filePath              = filePath;
            scanVC.orgName               = name;
            [self.navigationController pushViewController:scanVC animated:YES];
        }
    }else if ([eventName isEqualToString:GXRouterEventRedPacketTapEvent]) {
        //        [self clickRedPacketTaped:modelFrame.model];
    } else if ([eventName isEqualToString:GXRouterEventNoticeMessage]) {
        // 打开  可能是打开某个原生界面
        if (![ICTools stringEmpty:[userInfo objectForKey:@"url"]]) {
            [self pushCustomViewControllerURL:[userInfo objectForKey:@"url"]
                           fromViewController:self
                                     animated:YES];
        }
        
        if ([userInfo objectForKey:@"messageId"]) {
            // 更新具体某条消息是否已读
            NSString *meaasgeId = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"messageId"]];
            [self updateMessageReadStatus:meaasgeId];
            [self.tableView reloadData];
        }
    } else if ([eventName isEqualToString:GXRouterEventDrtNewsTapEvent]) {
       
    } else if ([eventName isEqualToString:GXRouterEventActivityEvent]) {
        NSDictionary *filekey =  [NSDictionary dictionaryWithJsonString:modelFrame.model.message.fileKey];
        if (![ICTools stringEmpty:[filekey objectForKey:@"url"]]) {
            [self pushCustomViewControllerURL:[filekey objectForKey:@"url"]
                           fromViewController:self
                                     animated:YES];
        }
    }
}

- (void)updateMessageReadStatus:(NSString *)messageId {
    // 更新具体某条消息是否已读
    [ICMessageDatabase updateMessageStatus:messageId
                                       gId:self.group.gId
                                    status:ICMessageStatus_read];
    NSDictionary *param = @{@"gId":self.group.gId,
                            @"msgIds":@[messageId]};
    
    [[ICMessageSocketManager sharedInstance] tdoReadChangeStatusParam:param identifier:@"0" Success:^(id object, id other) {
        NSLog(@"MessageRead%@", object);
    } Failure:^(NSError *error, id other) {
    }];
    for (ICMessageFrame *model in self.dataSource) {
        
        NSString *tempMessId = [NSString stringWithFormat:@"%@",model.model.message.messageId];
        if (tempMessId && [tempMessId isEqualToString:messageId]) {
            model.model.message.status = ICMessageStatus_read;
            break;
        }
    }
}

// tap image  聊天发送的图片
- (void)showLargeImageWithOglImage:(UIImage *)oglImage
                          WithPath:(NSString *)imgPath
                      withMessageF:(ICMessageFrame *)messageF
                          fromView:(UIView *)from
                       currentCell:(ICChatMessageBaseCell *)cell
{
    NSIndexPath *currentIndexthPath = [self.tableView indexPathForCell:cell];
    NSMutableArray *items = [[NSMutableArray alloc] init];
    UIView *fromView = nil;
    
    for (NSUInteger index = 0; index < self.dataSource.count; index++) {
        ICMessageFrame *modelFrame = [self.dataSource objectAtIndex:index];
        NSString *messageType = modelFrame.model.message.type;
        
        if ([messageType isEqualToString:TypePic]) {
            YYPhotoGroupItem *item = [YYPhotoGroupItem new];
            item.largeImageURL = [NSURL URLWithString:[ICTools getFileOglImageURL:(modelFrame.model.message.fileKey)]];
            item.oglImage = oglImage;
            if (currentIndexthPath.row == index) {
                fromView = from;
                item.thumbView = from;
            } else {
                item.thumbView = nil;
            }
            [items addObject:item];
        }
    }
    
    YYPhotoGroupView *v = [[YYPhotoGroupView alloc] initWithGroupItems:items];
    [v presentFromImageView:fromView toContainer:App_RootCtr.view fromViewC:self animated:YES completion:nil];
}

#pragma mark - getters and setters

-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.userInteractionEnabled = YES;
        _tableView.backgroundColor = BACKGROUNDCOLOR;
        self.extendedLayoutIncludesOpaqueBars = NO;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
    }
    return _tableView;
}



- (NSMutableArray *)dataSource
{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

-(ICEmptyStyleView *)emptyView {
    if (!_emptyView) {
        _emptyView = [[ICEmptyStyleView alloc] initWithTitle:@"暂无数据" placeholderImage:[UIImage imageNamedFromiComeSDKBundle:@"icon_message_empty"] imageURL:@""];
        _emptyView.hidden = YES;
        _emptyView.frame = CGRectMake(0, 0, App_Frame_Width, APP_Frame_Height);
        [self.view addSubview:_emptyView];
    }
    return _emptyView;
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
